package com.pengpeng.flash.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pengpeng.flash.common.R;
import com.pengpeng.flash.entity.Employee;
import com.pengpeng.flash.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    /**
     * 登录功能模块
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request,
                             @RequestBody Employee employee){
        //1.对获取到的密码进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据页面提交的用户名查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3.如果没有查询到则登录失败
        if (emp == null){
            return R.error("登录失败,用户名或密码错误");
        }

        //4.进行密码比对，若浏览器传来的面与数据库查询到的密码不一样，则登录失败
        if (!emp.getPassword().equals(password)){
            return R.error("登录失败,用户名或密码错误");
        }

        //5.检查用户状态，若为“禁用”，则登录失败
        if (emp.getStatus()==0){
            return R.error("账号已禁用");
        }
        //登陆成功，将员工id放到session中并返回结果
        request.getSession().setAttribute("empId",emp.getId());
        return R.success(emp);
    }

    /**
     * 退出功能模块
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("empId");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping  //请求路径是 /employee
    public R<String> insertEmployee(HttpServletRequest httpServletRequest,
                                    @RequestBody Employee employee){
        //对新增员工设置初始密码，使用md5加密技术
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置新增员工的创建时间和更新时间
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //设置新增员工的创建人和更新人
        //long empId = (long) httpServletRequest.getSession().getAttribute("empId");
        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);
        //保存员工
        employeeService.save(employee);
        return R.success("添加成功");
    }

    /**
     * 分页处理
     *
     * 此处如果在入参位置写了@RequestParam注解分别给每一个参数，那么SpringBoot底层会根据对应的请求专门找相应的controller方法
     * 例如http://localhost:8080/employee/page?page=1&pageSize=10请求，就必须有一个专门的controller方法标注了两个@RequestParam注解，
     * 若没有就会报错，而如果controller方法没有添加@RequestParam注解，则会自动注入入参，有则注入，没有则不注入
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Employee::getCreateTime);
        //执行查询
        employeeService.page(pageInfo,lambdaQueryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据id修改对应的员工信息
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,
                            @RequestBody Employee employee){
        //long empId = (long) request.getSession().getAttribute("empId");
        //设置员工更新时间
        //employee.setUpdateTime(LocalDateTime.now());
        //设置更新人
        //employee.setUpdateUser(empId);
        employeeService.updateById(employee);
        return R.success("状态修改成功");
    }

    /**
     * 根据id查询用户，响应到修改表单回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getEmployeeById(@PathVariable("id") long id){
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getId,id);
        Employee emp = employeeService.getOne(queryWrapper);
        return R.success(emp);
    }
}
